package com.newear.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.newear.MyApplication;
import com.newear.R;
import com.newear.base.ui.PullToRefreshView;
import com.newear.bean.HistoryRecordInfo;
import com.newear.bean.ReportInfo;
import com.newear.constant.DataType;
import com.newear.constant.RequireParams;
import com.newear.happyDialog.HistoryDateDialog;
import com.newear.message.MessageDispatcher;
import com.newear.message.MessageType;
import com.newear.util.HardWare;
import com.newear.util.MyLogger;
import com.newear.util.ProgressDialogUtil;
import com.newear.util.T;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class HappyHistoryActivity extends AppCompatActivity {
    private static final String TAG = "HappyHistoryActivity";
    private ImageView img_history_close;
    private LinearLayout lL_history_date;//日期检索
    private TextView tv_history_year_day;//检索时间
    private Context mContext;
    private ListView history_report_list;
    private MyReportAdapter mReportAdapter;
    private String dateStr;
    private String key;
    private MyHandler myHandler;
    private ProgressDialog mProgressDialog; //网络请求时用的进度条
    private HistoryRecordInfo mHistoryRecordInfo;
    private PullToRefreshView pullToRefreshView;
    private List<ReportInfo> reportInfoList;
    /**
     * 更新类型，包括刷新和加载更多
     */
    private int action = 0;

    private interface UpdateType {
        int NORMAL = 0;
        int REFRESH = 1;
        int ONMORE = 2;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.happy_history_activity);
        mContext = this;
        init();
        findViews();
        setListeners();
        initReportListView();
    }

    private void init(){
        reportInfoList = new ArrayList<>();
        this.mContext = this;
        this.key = this.hashCode() + "";
        myHandler = new MyHandler(this);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        dateStr = HardWare.getCurDate2();
        getReport(1);
    }

    private void findViews(){
        pullToRefreshView = (PullToRefreshView) findViewById(R.id.refreshable_view);
        pullToRefreshView.setNeedGetMoreData(true);
        pullToRefreshView.setNeedGetNewData(true);
        pullToRefreshView.setFootMode(PullToRefreshView.FootViewMode.ClickAble);
        pullToRefreshView.setOnRefreshListener(refreshListener);
        img_history_close = (ImageView) findViewById(R.id.img_history_close);
        lL_history_date = (LinearLayout) findViewById(R.id.lL_history_date);
        tv_history_year_day = (TextView) findViewById(R.id.tv_history_year_day);
        tv_history_year_day.setText(HardWare.getCurDate());
        //报告列表
        history_report_list = (ListView) findViewById(R.id.history_report_list);

    }

    private void setListeners(){
        img_history_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //弹出日历
        lL_history_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HistoryDateDialog dataDialog = new HistoryDateDialog(mContext,R.style.dialog);
                dataDialog.setOnSelectedListener(new HistoryDateDialog.OnSelectedListener() {
                    @Override
                    public void onDayClicked(int y, int m, int d) {
                        tv_history_year_day.setText(y + "年" + m + "月" + d + "日 ");
                        dateStr = y + "-" + m + "-" + d;
                        getReport( 1);
                    }
                });
                dataDialog.show();
            }
        });
    }

    private void goReport(int reportId) {
        Intent intent = new Intent(mContext, HappyReportActivity.class);
        intent.putExtra("id", reportId);
        startActivity(intent);
    }

    private void initReportListView() {
        mReportAdapter = new MyReportAdapter();
        history_report_list.setAdapter(mReportAdapter);
    }


    class MyReportAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (reportInfoList != null ) {
                return reportInfoList.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HistoryListViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.item_history_report, null);
                holder = new HistoryListViewHolder();
                holder.img_report = (ImageView) convertView.findViewById(R.id.img_report);
                holder.tv_user_health = (TextView) convertView.findViewById(R.id.tv_user_health);
                holder.tv_report_date = (TextView) convertView.findViewById(R.id.tv_report_date);
                holder.btn_look_report = (Button) convertView.findViewById(R.id.btn_look_report);
                convertView.setTag(holder);
            } else {
                holder = (HistoryListViewHolder) convertView.getTag();
            }
            final ReportInfo reportInfo = reportInfoList.get(position);
            if (reportInfo != null) {
                List<ReportInfo.Symptom> symptomList =  reportInfo.symptomList;
                String symptomStr = "";
                if (symptomList != null) {
                    for (int i = 0; i< symptomList.size(); i++) {
                        symptomStr += (symptomList.get(i).name + " ");
                    }
                }
                Glide.with(mContext).load(reportInfo.faceThumbUrl).into(holder.img_report);
                holder.tv_user_health.setText(symptomStr);
                holder.tv_report_date.setText(reportInfo.displayTime);
                holder.btn_look_report.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        goReport(reportInfo.id);
                    }
                });
            }
            return convertView;
        }

        class HistoryListViewHolder {
            TextView tv_user_health,tv_report_date;
            ImageView img_report;
            Button btn_look_report;
        }

    }

    /**
     * 得到报告
     * @param page
     */
    private void getReport(int page) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.DATA_TYPE, DataType.HISTORY_REPORT);
        param.put(RequireParams.MAP_KEY, this.key + DataType.HISTORY_REPORT);
        param.put(RequireParams.DATE, dateStr);
        param.put(RequireParams.PAGE, page);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    private void showReportInfo() {
        List<ReportInfo> tempReportInfos = mHistoryRecordInfo.reportInfos;
        if (action == UpdateType.ONMORE) {  //如果是上拉加载更多，则加入
            reportInfoList.addAll(tempReportInfos);
        } else {
            reportInfoList.clear();
            reportInfoList.addAll(tempReportInfos);
        }
        mReportAdapter.notifyDataSetChanged();
    }

    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final HappyHistoryActivity activity = (HappyHistoryActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.setMessage("正在获取历史报告...");
                                activity.mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.HISTORY_REPORT) {
                                SparseArray<Object> result = (SparseArray<Object>) msg.obj;
                                String errno = (String) result.get(0);
                                if ("0".equals(errno)) {
                                    HistoryRecordInfo historyRecordInfo = (HistoryRecordInfo) result.get(1);
                                    if (historyRecordInfo != null) {
                                        activity.mHistoryRecordInfo = historyRecordInfo;
                                        activity.showReportInfo();
                                    }
                                } else if ("1".equals(errno)){
                                    String errMsg = (String) result.get(1);
                                    T.shortToast(activity, errMsg);
                                }
                                /** 处理刷新和上拉加载更多的界面 **/
                                if (activity.action == UpdateType.REFRESH || activity.action == UpdateType.ONMORE) {
                                    if (activity.action == UpdateType.REFRESH) {
                                        activity.pullToRefreshView.onHeaderRefreshComplete();
                                        activity.pullToRefreshView.scrollToPosition(0);
                                    }
                                    activity.pullToRefreshView.onComplete(false);
                                    activity.action = UpdateType.NORMAL;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "handleMessage Exception!e:" + e.getMessage());
            }
        }
    }

    PullToRefreshView.OnRefreshListener refreshListener = new PullToRefreshView.OnRefreshListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub
            //刷新完成以后
            action = UpdateType.REFRESH;
            getReport(1);
        }

        @Override
        public boolean onMore(int nextPageNum) {
            // TODO Auto-generated method stub
            if (mHistoryRecordInfo != null && mHistoryRecordInfo.curr < mHistoryRecordInfo.pages) {
                action = UpdateType.ONMORE;
                getReport(mHistoryRecordInfo.curr + 1);
            } else {
                T.shortToast(mContext, getResources().getString(R.string.no_more_info));
                action = UpdateType.NORMAL;
                pullToRefreshView.onComplete(false);

            }
            return false;
        }

        @Override
        public void onGetPageData() {
            // TODO Auto-generated method stub
        }
    };
}
